package service.impl;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import model.MUser;
import service.interf.IUser;
import dao.interf.IUserDao;
import dao.pojo.User;

public class UserImpl implements IUser {
	private IUserDao userDao;

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	public String login(MUser model) {
		User u = userDao.getByProperty("name" , model.getName());
		if (u == null) {
			return "0";
		} else {
			if (u.getPassword().equals(model.getPassword())) {
				return "1";
			} else {
				return "0";
			}
		}
	}
	
	public String getUser(MUser model) {
		User u = userDao.getById(model.getId());
		JSONObject obj = new JSONObject();
		obj.put("id", u.getId());
		obj.put("name", u.getName());
		obj.put("password", u.getPassword());
		obj.put("email", u.getEmail());
		return obj.toString();
	}
	
	public String getAllUser() {
		List<User> list = (List<User>)userDao.getAll();
		JSONArray jarr = new JSONArray();
		JSONObject obj = new JSONObject();
		for (User u : list) {
			obj.clear();
			obj.put("id", u.getId());
			obj.put("name", u.getName());
			obj.put("password", u.getPassword());
			obj.put("email", u.getEmail());
			jarr.add(obj);
		}
		return jarr.toString();
	}
	
	public String register(String name, String password, String email) {
		User u = new User();
		u.setEmail(email);
		u.setName(name);
		u.setPassword(password);
		
		return userDao.add(u);		
	}
	
}
